<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理仪表盘 - 校园报投稿系统</title>
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .dashboard-container {
            padding: 20px;
        }
        
        .dashboard-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .dashboard-title {
            font-size: 1.8rem;
            color: #444;
        }
        
        .admin-actions {
            display: flex;
            gap: 10px;
        }
        
        .logout-btn {
            background-color: #dc3545;
            color: white;
        }
        
        .logout-btn:hover {
            background-color: #c82333;
        }
        
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            text-align: center;
        }
        
        .stat-card h3 {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 10px;
            font-weight: normal;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .submissions-table {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .table-header {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .table-title {
            font-size: 1.3rem;
            color: #444;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .status {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-approved {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background-color: #138496;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }
        
        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .pagination button.active {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .modal-content {
            max-width: 800px;
        }
        
        .submission-detail {
            line-height: 1.8;
        }
        
        .submission-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .submission-meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #666;
        }
        
        .submission-meta-label {
            font-weight: 600;
            color: #444;
        }
        
        .submission-content {
            white-space: pre-wrap;
            color: #555;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <div class="dashboard-header">
            <h1 class="dashboard-title">管理仪表盘</h1>
            <div class="admin-actions">
                <button class="btn btn-secondary">设置</button>
                <button class="btn logout-btn" onclick="logout()">退出登录</button>
            </div>
        </div>
        
        <div class="stats-cards">
            <div class="stat-card">
                <h3>总投稿数</h3>
                <div class="stat-number"></div>
            </div>
            <div class="stat-card">
                <h3>待审核</h3>
                <div class="stat-number"></div>
            </div>
            <div class="stat-card">
                <h3>已通过</h3>
                <div class="stat-number"></div>
            </div>
            <div class="stat-card">
                <h3>已拒绝</h3>
                <div class="stat-number"></div>
            </div>
        </div>
        
        <div class="submissions-table">
        <div class="table-header">
            <h2 class="table-title">投稿列表</h2>
        </div>
            
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>作者</th>
                        <th>年级/班级</th>
                        <th>分类</th>
                        <th>提交时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 数据将通过API加载 -->
                    <tr>
                        <td colspan="8" style="text-align: center; color: #999; padding: 30px;">
                            正在加载数据...
                        </td>
                    </tr>
                </tbody>
            </table>
            
            <div class="pagination">
                <button disabled>上一页</button>
                <button class="active">1</button>
                <button>2</button>
                <button>3</button>
                <button>下一页</button>
            </div>
        </div>
    </div>

    <!-- 投稿详情模态框 -->
    <div id="submissionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>投稿详情</h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="detail-item">
                    <span class="detail-label">标题:</span>
                    <span id="detailTitle" class="detail-value"></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">作者:</span>
                    <span id="detailAuthor" class="detail-value"></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">年级/班级:</span>
                    <span id="detailGradeClass" class="detail-value"></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">分类:</span>
                    <span id="detailCategory" class="detail-value"></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">提交时间:</span>
                    <span id="detailTime" class="detail-value"></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">状态:</span>
                    <span id="detailStatus" class="detail-value"></span>
                </div>
                <div class="detail-item detail-content">
                    <span class="detail-label">内容:</span>
                    <p id="detailContent" class="detail-value content-text"></p>
                </div>
            </div>
            <!-- 添加模态框底部按钮区域 -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="deleteSubmission(currentSubmissionId, document.getElementById('detailTitle').textContent)">删除</button>
                <button type="button" class="btn btn-secondary" onclick="closeModal()">关闭</button>
            </div>
        </div>
    </div>
    
    <!-- 添加额外样式 -->
    <style>
        /* 模态框底部样式 */
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            padding: 15px;
            border-top: 1px solid #e9ecef;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }
        
        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }
        
        .btn-primary {
            background-color: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #5a67d8;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background-color: #138496;
        }
        
        /* 操作按钮容器 */
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        /* 分页按钮样式 */
        .pagination button {
            margin: 0 2px;
            padding: 5px 10px;
            border: 1px solid #ddd;
            background: #fff;
            cursor: pointer;
            border-radius: 3px;
        }
        
        .pagination button.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }
    </style>

    <script>
        // 当前页面和状态筛选
        let currentPage = 1;
        let currentStatus = null;
        let currentSubmissionId = null;
        
        // 检查登录状态并连接到生产环境API
        async function checkLogin() {
            const adminToken = localStorage.getItem('adminToken');
            const adminInfo = localStorage.getItem('adminInfo');
            
            if (!adminToken) {
                // 如果没有token，重定向到登录页面
                window.location.href = 'index.html';
                return;
            }
            
            // 尝试验证token有效性
            try {
                const apiUrl = window.location.origin + '/api/admin/verify';
                console.log('正在验证会话...');
                
                const response = await fetch(apiUrl, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + adminToken
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // Token有效，显示管理员信息
                    displayAdminInfo(data.admin);
                } else {
                    // Token无效，清除本地存储并重定向到登录页面
                    clearLocalStorage();
                }
            } catch (err) {
                console.error('会话验证错误:', err);
                
                // 作为备用方案，检查本地存储的adminInfo
                if (adminInfo) {
                    try {
                        const admin = JSON.parse(adminInfo);
                        displayAdminInfo(admin);
                        console.log('使用本地存储的管理员信息');
                    } catch (parseErr) {
                        clearLocalStorage();
                    }
                } else {
                    clearLocalStorage();
                }
            }
        }
        
        // 退出登录
        async function logout() {
            const adminToken = localStorage.getItem('adminToken');
            try {
                // 尝试调用登出API
                const apiUrl = window.location.origin + '/api/admin/logout';
                await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + adminToken
                    }
                });
            } catch (error) {
                console.log('登出API调用失败，但仍会清除本地存储');
            } finally {
                // 无论API调用成功与否，都清除本地存储并重定向
                clearLocalStorage();
            }
        }
        
        // 显示管理员信息
        function displayAdminInfo(admin) {
            // 显示欢迎信息
            const welcomeElement = document.createElement('div');
            welcomeElement.className = 'welcome-message';
            welcomeElement.textContent = `欢迎您，${admin.username || '管理员'}！`;
            welcomeElement.style.position = 'absolute';
            welcomeElement.style.top = '20px';
            welcomeElement.style.left = '50%';
            welcomeElement.style.transform = 'translateX(-50%)';
            welcomeElement.style.color = '#666';
            welcomeElement.style.fontSize = '0.9rem';
            
            // 将欢迎信息添加到页面头部
            const dashboardHeader = document.querySelector('.dashboard-header');
            if (dashboardHeader) {
                dashboardHeader.appendChild(welcomeElement);
            }
            
            // 添加刷新统计数据的功能
            refreshDashboardStats();
        }
        
        // 清除本地存储并重定向到登录页面
        function clearLocalStorage() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminInfo');
            localStorage.removeItem('adminLoggedIn');
            window.location.href = 'index.html';
        }
        
        // 刷新仪表盘统计数据
        async function refreshDashboardStats() {
            const adminToken = localStorage.getItem('adminToken');
            if (!adminToken) return;
            
            try {
                const apiUrl = window.location.origin + '/api/admin/stats';
                const response = await fetch(apiUrl, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + adminToken
                    }
                });
                
                const data = await response.json();
                if (data.success && data.stats) {
                    // 更新统计数据显示
                    updateStatsDisplay(data.stats);
                } else {
                    // 数据获取失败时显示NaN
                    updateStatsDisplay({
                        total: NaN,
                        pending: NaN,
                        approved: NaN,
                        rejected: NaN
                    });
                }
            } catch (err) {
                console.log('获取统计数据失败');
                // 错误时显示NaN
                updateStatsDisplay({
                    total: NaN,
                    pending: NaN,
                    approved: NaN,
                    rejected: NaN
                });
            }
        }
        
        // 更新统计数据显示
        function updateStatsDisplay(stats) {
            // 查找并更新统计卡片中的数字
            const cards = document.querySelectorAll('.stat-card');
            if (cards.length > 0) {
                if (cards[0].querySelector('.stat-number')) {
                    cards[0].querySelector('.stat-number').textContent = stats.total || 0;
                }
                if (cards[1] && cards[1].querySelector('.stat-number')) {
                    cards[1].querySelector('.stat-number').textContent = stats.pending || 0;
                }
                if (cards[2] && cards[2].querySelector('.stat-number')) {
                    cards[2].querySelector('.stat-number').textContent = stats.approved || 0;
                }
                if (cards[3] && cards[3].querySelector('.stat-number')) {
                    cards[3].querySelector('.stat-number').textContent = stats.rejected || 0;
                }
            }
        }
        
        // 获取投稿列表
        async function loadSubmissions(page = 1, status = null) {
            try {
                currentPage = page;
                currentStatus = status;
                
                // 获取存储的token
                const adminToken = localStorage.getItem('adminToken');
                
                // 构建URL查询参数
                let url = window.location.origin + `/api/submissions?page=${page}&limit=20`;
                if (status !== null) {
                    url += `&status=${status}`;
                }
                
                // 添加身份验证
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Authorization': adminToken ? 'Bearer ' + adminToken : ''
                    }
                });
                
                const data = await response.json();
                
                if (data.success || response.ok) {
                    renderSubmissions(data.data || []);
                    renderPagination(data.pagination || { page: page, totalPages: 1, hasPrev: false, hasNext: false });
                    updateStats();
                } else {
                    renderSubmissions([]);
                    showMessage('获取投稿列表失败', 'error');
                }
            } catch (error) {
                console.error('加载投稿失败:', error);
                // 错误时显示空列表
                renderSubmissions([]);
                showMessage('无法连接到服务器', 'error');
            }
        }
        
        // 渲染投稿列表
        function renderSubmissions(submissions) {
            const tableBody = document.querySelector('table tbody');
            tableBody.innerHTML = '';
            
            if (submissions.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="8" style="text-align: center; color: #999; padding: 30px;">
                            暂无投稿数据
                        </td>
                    </tr>
                `;
                return;
            }
            
            submissions.forEach(submission => {
                const row = document.createElement('tr');
                
                // 获取状态显示
                let statusClass = '';
                let statusText = '';
                switch (submission.status) {
                    case 0:
                        statusClass = 'status-pending';
                        statusText = '待审核';
                        break;
                    case 1:
                        statusClass = 'status-approved';
                        statusText = '已通过';
                        break;
                    case 2:
                        statusClass = 'status-rejected';
                        statusText = '已拒绝';
                        break;
                }
                
                // 获取分类显示
                const categoryMap = {
                    1: '校园故事',
                    2: '学习心得',
                    3: '科技创新',
                    4: '艺术文化',
                    5: '体育活动',
                    6: '其他'
                };
                
                let actions = `
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-info" onclick="viewSubmission(${submission.id})">查看</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteSubmission(${submission.id}, '${submission.title}')">删除</button>
                    </div>
                `;
                
                // 如果是待审核状态，显示审核按钮
                if (submission.status === 0) {
                    actions = `
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-info" onclick="viewSubmission(${submission.id})">查看</button>
                            <button class="btn btn-sm btn-success" onclick="updateSubmissionStatus(${submission.id}, 1)">通过</button>
                            <button class="btn btn-sm btn-danger" onclick="updateSubmissionStatus(${submission.id}, 2)">拒绝</button>
                        </div>
                    `;
                }
                
                row.innerHTML = `
                    <td>${submission.id}</td>
                    <td>${submission.title}</td>
                    <td>${submission.name}</td>
                    <td>${submission.grade}年级/${submission.class}班</td>
                    <td>${categoryMap[submission.category] || '其他'}</td>
                    <td>${formatDateTime(submission.submitted_at)}</td>
                    <td><span class="status ${statusClass}">${statusText}</span></td>
                    <td>${actions}</td>
                `;
                
                tableBody.appendChild(row);
            });
        }
        
        // 渲染分页
        function renderPagination(pagination) {
            const paginationContainer = document.querySelector('.pagination');
            paginationContainer.innerHTML = '';
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = !pagination.hasPrev;
            prevBtn.onclick = () => loadSubmissions(pagination.page - 1, currentStatus);
            paginationContainer.appendChild(prevBtn);
            
            // 页码按钮（简化版）
            for (let i = 1; i <= pagination.totalPages; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                if (i === pagination.page) {
                    pageBtn.classList.add('active');
                }
                pageBtn.onclick = () => loadSubmissions(i, currentStatus);
                paginationContainer.appendChild(pageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = !pagination.hasNext;
            nextBtn.onclick = () => loadSubmissions(pagination.page + 1, currentStatus);
            paginationContainer.appendChild(nextBtn);
        }
        
        // 查看投稿详情
        async function viewSubmission(id) {
            try {
                currentSubmissionId = id;
                
                const response = await fetch(`/api/submissions/${id}`);
                const data = await response.json();
                
                if (data.success) {
                    const submission = data.data;
                    
                    // 获取状态显示
                    const statusMap = { 0: '待审核', 1: '已通过', 2: '已拒绝' };
                    
                    // 获取分类显示
                    const categoryMap = {
                        1: '校园故事',
                        2: '学习心得',
                        3: '科技创新',
                        4: '艺术文化',
                        5: '体育活动',
                        6: '其他'
                    };
                    
                    document.getElementById('detailTitle').textContent = submission.title || 'NaN';
                    document.getElementById('detailAuthor').textContent = submission.name || 'NaN';
                    document.getElementById('detailGradeClass').textContent = submission.grade && submission.class ? `${submission.grade}年级/${submission.class}班` : 'NaN';
                    document.getElementById('detailCategory').textContent = categoryMap[submission.category] || 'NaN';
                    document.getElementById('detailTime').textContent = submission.submitted_at ? formatDateTime(submission.submitted_at) : 'NaN';
                    document.getElementById('detailStatus').textContent = statusMap[submission.status] || 'NaN';
                    document.getElementById('detailContent').textContent = submission.content || 'NaN';
                    
                    // 更新模态框底部按钮
                    const modalFooter = document.querySelector('#submissionModal .modal-footer');
                    
                    if (submission.status === 0) {
                        modalFooter.innerHTML = `
                            <button type="button" class="btn btn-success" onclick="updateSubmissionStatus(${submission.id}, 1)">通过</button>
                            <button type="button" class="btn btn-danger" onclick="updateSubmissionStatus(${submission.id}, 2)">拒绝</button>
                            <button type="button" class="btn btn-danger" onclick="deleteSubmission(${submission.id}, '${submission.title || 'NaN'}')">删除</button>
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">关闭</button>
                        `;
                    } else {
                        modalFooter.innerHTML = `
                            <button type="button" class="btn btn-danger" onclick="deleteSubmission(${submission.id}, '${submission.title || 'NaN'}')">删除</button>
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">关闭</button>
                        `;
                    }
                    
                    const modal = document.getElementById('submissionModal');
                    modal.style.display = 'flex';
                    document.body.style.overflow = 'hidden';
                } else {
                    showMessage('获取投稿详情失败', 'error');
                }
            } catch (error) {
                console.error('查看投稿详情失败:', error);
                showMessage('查看投稿详情失败', 'error');
            }
        }
        
        // 更新投稿状态
        async function updateSubmissionStatus(id, status) {
            const adminToken = localStorage.getItem('adminToken');
            const statusText = status === 1 ? '通过' : '拒绝';
            
            try {
                const apiUrl = window.location.origin + `/api/submissions/${id}/status`;
                const response = await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': adminToken ? 'Bearer ' + adminToken : ''
                    },
                    body: JSON.stringify({ status })
                });
                
                // 无论响应状态如何，都先刷新数据，确保用户看到最新状态
                // 关闭模态框
                closeModal();
                
                // 重新加载数据
                loadSubmissions(currentPage, currentStatus);
                refreshDashboardStats(); // 同时刷新统计数据
                
                // 然后根据响应状态显示适当的消息
                if (!response.ok) {
                    // 请求失败，但数据可能已更新，显示警告而非错误
                    console.warn('更新状态请求返回非成功状态:', response.status);
                    showMessage(`投稿${statusText}操作已提交，请确认最新状态`, 'warning');
                    return;
                }
                
                // 请求成功，显示成功消息
                showMessage(`投稿已${statusText}`, 'success');
            } catch (error) {
                console.error('更新投稿状态失败:', error);
                // 即使发生错误，也尝试刷新数据并显示警告而非错误
                loadSubmissions(currentPage, currentStatus);
                refreshDashboardStats();
                showMessage(`投稿${statusText}操作已提交，请确认最新状态`, 'warning');
            }
        }
        
        // 删除投稿（使用软删除）
        async function deleteSubmission(id, title) {
            if (confirm(`确定要删除投稿「${title}」吗？此操作不可撤销，但数据会被软删除保留。`)) {
                try {
                    const response = await fetch(`/api/submissions/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    // 无论响应状态如何，都先刷新数据，确保用户看到最新状态
                    // 关闭模态框
                    closeModal();
                    
                    // 重新加载数据
                    loadSubmissions(currentPage, currentStatus);
                    refreshDashboardStats(); // 同时刷新统计数据
                    
                    // 然后根据响应状态显示适当的消息
                    if (!response.ok) {
                        // 请求失败，但数据可能已更新，显示警告而非错误
                        console.warn('删除请求返回非成功状态:', response.status);
                        showMessage('投稿删除操作已提交，请确认最新状态', 'warning');
                        return;
                    }
                    
                    // 请求成功，显示成功消息
                    showMessage('投稿已成功删除', 'success');
                } catch (error) {
                    console.error('删除投稿失败:', error);
                    // 即使发生错误，也尝试刷新数据并显示警告而非错误
                    loadSubmissions(currentPage, currentStatus);
                    refreshDashboardStats();
                    showMessage('投稿删除操作已提交，请确认最新状态', 'warning');
                }
            }
        }
        
        // 关闭模态框
        function closeModal() {
            const modal = document.getElementById('submissionModal');
            modal.style.display = 'none';
            document.body.style.overflow = '';
            currentSubmissionId = null;
        }
        
        // 根据ID查询投稿
        async function searchSubmissionById() {
            const idInput = document.getElementById('searchByIdInput');
            const id = idInput.value.trim();
            const resultContainer = document.getElementById('searchResult');
            
            if (!id || isNaN(id)) {
                showMessage('请输入有效的投稿ID', 'error');
                return;
            }
            
            try {
                const response = await fetch(`/api/submissions/${id}`);
                const data = await response.json();
                
                if (data.success && data.data) {
                    const submission = data.data;
                    
                    // 获取状态显示
                    const statusMap = { 0: '待审核', 1: '已通过', 2: '已拒绝' };
                    
                    // 构建结果显示内容
                    resultContainer.innerHTML = `
                        <div class="search-result">
                            <div class="search-result-item">
                                <span class="search-result-label">投稿编号(ID):</span>
                                <span>${submission.id}</span>
                            </div>
                            <div class="search-result-item">
                                <span class="search-result-label">投稿人:</span>
                                <span>${submission.name || '未知'}</span>
                            </div>
                            <div class="search-result-item">
                                <span class="search-result-label">年级/班级:</span>
                                <span>${submission.grade ? `${submission.grade}年级/${submission.class || ''}班` : '未知'}</span>
                            </div>
                            <div class="search-result-item">
                                <span class="search-result-label">投稿标题:</span>
                                <span>${submission.title || '无标题'}</span>
                            </div>
                            <div class="search-result-item">
                                <span class="search-result-label">审核结果:</span>
                                <span>${statusMap[submission.status] || '未知'}</span>
                            </div>
                            <div class="search-result-item">
                                <span class="search-result-label">提交时间:</span>
                                <span>${formatDateTime(submission.submitted_at)}</span>
                            </div>
                            <div style="margin-top: 10px;">
                                <button class="btn btn-sm btn-info" onclick="viewSubmission(${submission.id})">查看详细内容</button>
                                <button class="btn btn-sm btn-secondary" onclick="document.getElementById('searchResult').style.display = 'none';">关闭结果</button>
                            </div>
                        </div>
                    `;
                    
                    resultContainer.style.display = 'block';
                    // 滚动到结果区域
                    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
                } else {
                    showMessage('未找到对应ID的投稿记录', 'error');
                    resultContainer.style.display = 'none';
                }
            } catch (error) {
                console.error('查询投稿失败:', error);
                showMessage('查询失败，请稍后重试', 'error');
                resultContainer.style.display = 'none';
            }
        }
        
        // 格式化日期时间
        function formatDateTime(timestamp) {
            if (!timestamp) return '-';
            
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 显示消息提示（简单实现）
        function showMessage(message, type = 'info') {
            // 创建消息元素
            const messageDiv = document.createElement('div');
            messageDiv.textContent = message;
            messageDiv.style.position = 'fixed';
            messageDiv.style.top = '20px';
            messageDiv.style.right = '20px';
            messageDiv.style.padding = '12px 20px';
            messageDiv.style.borderRadius = '5px';
            messageDiv.style.color = 'white';
            messageDiv.style.zIndex = '10000';
            messageDiv.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
            messageDiv.style.transition = 'opacity 0.3s';
            
            // 设置不同类型的样式
            switch (type) {
                case 'success':
                    messageDiv.style.backgroundColor = '#28a745';
                    break;
                case 'error':
                    messageDiv.style.backgroundColor = '#dc3545';
                    break;
                case 'warning':
                    messageDiv.style.backgroundColor = '#ffc107';
                    messageDiv.style.color = '#333';
                    break;
                default:
                    messageDiv.style.backgroundColor = '#667eea';
            }
            
            document.body.appendChild(messageDiv);
            
            // 3秒后淡出
            setTimeout(() => {
                messageDiv.style.opacity = '0';
                setTimeout(() => {
                    messageDiv.remove();
                }, 300);
            }, 3000);
        }
        
        // 更新统计数据 (兼容旧版API调用)
        function updateStats() {
            // 调用新版的刷新统计数据函数
            refreshDashboardStats();
        }
        
        // 移除所有模拟数据函数
        
        // 页面加载时检查登录状态
        window.addEventListener('DOMContentLoaded', () => {
            checkLogin();
        });
        
        // 页面加载完成后加载数据
        window.addEventListener('load', function() {
            loadSubmissions();
        });
    </script>
</body>
</html>